package com.qilu.pe.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.qilu.pe.MainActivity;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.WxUserInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PermissionUtil;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.List;

import androidx.appcompat.widget.AppCompatEditText;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class LoginActivity extends Base2Activity {
    private TextView tv_ok;// 登录
    private AppCompatEditText et_phone, et_pwd;// 手机号，密码
    private TextView tv_1, tv_5, tv_4, tv_2;// 阅读用户协议,注册,验证码登录
    private CheckBox cb_check;
    private LinearLayout ll_wx_login;// 微信登录

    private int LOGIN_TYPE = 0;// 0 普通登录 1 微信登录
    private WxUserInfo wxUserInfo;// 微信登录后解析的微信用户对象

    private static final String APP_ID = Config.WX_APP_ID;

    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;
    SendAuth.Req req;

    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        // 将应用的appId注册到微信
        api.registerApp(APP_ID);
        //建议动态监听微信启动广播进行注册到微信
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 将该app注册到微信
                api.registerApp(APP_ID);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));

    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_ok = findViewById(R.id.tv_ok);
        et_phone = findViewById(R.id.et_phone);
        et_pwd = findViewById(R.id.et_pwd);
        tv_1 = findViewById(R.id.tv_1);
        tv_2 = findViewById(R.id.tv_2);
        tv_5 = findViewById(R.id.tv_5);
        tv_4 = findViewById(R.id.tv_4);
        cb_check = findViewById(R.id.cb_check);
        ll_wx_login = findViewById(R.id.ll_wx_login);

        String user = Arad.preferences.getString(Config.USER_PREF_KEY);
        String pwd = Arad.preferences.getString(Config.PASSWORD_PREF_KEY);
        if (!TextUtils.isEmpty(user) && !TextUtils.isEmpty(pwd)) {
            et_phone.setText(user);
            et_pwd.setText(pwd);
        } else {
//            et_phone.setText("17612746598");
//            et_pwd.setText("123456789");
        }

        setOnClickListener(tv_ok, tv_1, tv_5, tv_4, tv_2, ll_wx_login);

        regToWx();// 注册微信api
        req = new SendAuth.Req();
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String userInfoJson = Arad.preferences.getString("userInfo");
                Logg.i("LoginActivity.onResume().userInfoJson = " + userInfoJson);
                if (LOGIN_TYPE == 1 && !TextUtils.isEmpty(userInfoJson)) {
                    Gson gson = new Gson();
                    wxUserInfo = gson.fromJson(userInfoJson, WxUserInfo.class);

                    Logg.i("wxUserInfo = " + wxUserInfo.toString());

                    hideProgress();
                    reqWxLogin(wxUserInfo.getUnionid(), wxUserInfo.getHeadimgurl());
                    showProgress();
                }
            }
        }, 100);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == ll_wx_login) {
            LOGIN_TYPE = 1;// 登录类型设置为微信
            req.scope = "snsapi_userinfo,snsapi_friend,snsapi_message,snsapi_contact";
            req.state = "none";
            api.sendReq(req);
        }
        if (v == tv_1) {// 阅读用户协议
            cb_check.setChecked(!cb_check.isChecked());
        }
        if (v == tv_2) {
            startActivity(UserAgreeActivity.class);
            LOGIN_TYPE = 0;// 登录类型设置为普通
        }
        if (v == tv_5) {// 注册
            startActivity(RegistActivity.class);
            LOGIN_TYPE = 0;// 登录类型设置为普通
        }
        if (v == tv_4) {//验证码登录
            startActivity(SmsCodeLoginActivity.class);
            LOGIN_TYPE = 0;// 登录类型设置为普通
        }
        if (v == tv_ok) {
            LOGIN_TYPE = 0;// 登录类型设置为普通
            PermissionUtil.handleMultiPermission(this, "定位,拍照",
                    new PermissionUtil.PermissionListener() {
                        @Override
                        public void onPermissionOk(boolean isOk) {
                            if (isOk) {
                                String phone = et_phone.getText().toString().trim();
                                String pwd = et_pwd.getText().toString().trim();

                                Arad.preferences.putString(Config.USER_PREF_KEY, phone).flush();
                                Arad.preferences.putString(Config.PASSWORD_PREF_KEY, pwd).flush();

                                if (!cb_check.isChecked()) {
                                    ToastUtils.showShort("请阅读并同意《用户服务协议》");
                                    return;
                                }
                                if (TextUtils.isEmpty(phone)) {
                                    ToastUtils.showShort("请输入手机号");
                                    return;
                                }
                                if (TextUtils.isEmpty(pwd)) {
                                    ToastUtils.showShort("请输入密码");
                                    return;
                                }
                                login(phone, pwd);
                                showProgressWithText(true, "登录中..");
                            } else {
                                ToastUtils.showShort("权限不足");
                            }
                        }

                        @Override
                        public void onOpenPermissionPage(boolean isOpen) {

                        }
                    }, Manifest.permission.CAMERA, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
        }
    }

    // 微信登录
    private Disposable reqWxLogin(String unionId, String pic) {
        return APIRetrofit.getDefault().wxLogin(unionId, "1", pic, "", "", "")
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            List<LinkedTreeMap<String, LinkedTreeMap<String, String>>> loginList = (List) baseResult2.getData();
                            if (loginList.size() >= 1) {
                                Logg.i("loginList.get(0) = " + loginList.get(0).getClass());
                                Logg.i("loginList.get(0) = " + loginList.get(0).get("original").getClass());

                                Global.HEADER = loginList.get(0).get("original").get("token_type") + " " + loginList.get(0).get("original").get("access_token");
                                startActivity(MainActivity.class);
                                finish();
                            }
                        } else {
                            if (TextUtils.equals("4001", baseResult2.getCode())) {// 注册成功,完善信息
                                LinkedTreeMap<String, Integer> user = (LinkedTreeMap) baseResult2.getData();
                                String tmp = user.get("id") + "";
                                if (tmp.contains(".")) {
                                    Global.USER_ID = tmp.substring(0, tmp.lastIndexOf("."));
                                } else {
                                    Global.USER_ID = tmp;
                                }
                                Logg.i("Global.USER_ID = " + Global.USER_ID);
                                startActivity(RealAuthAgentActivity.class);
                                LOGIN_TYPE = 0;// 登录类型设置为普通
                            } else if (TextUtils.equals("4002", baseResult2.getCode())) {// 微信绑定手机号
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("wxUserInfo", wxUserInfo);// 微信用户对象
                                startActivity(BindPhoneActivity.class, bundle);
                                LOGIN_TYPE = 0;// 登录类型设置为普通
                            }
                        }
                        ToastUtils.showShort(baseResult2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("登录失败");
                    }
                });
    }

    // 登录
    private Disposable login(String phone, String pwd) {
        return APIRetrofit.getDefault().login(phone, pwd, "1")
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
//                            List<Login> loginList = (List<Login>) baseResult2.getData();
                            List<LinkedTreeMap<String, LinkedTreeMap<String, String>>> loginList = (List) baseResult2.getData();
                            if (loginList.size() >= 1) {
//                                Login.Original original = loginList.get(0).getOriginal();
//                                Global.HEADER = original.getToken_type() + " " + original.getAccess_token();

                                Logg.i("loginList.get(0) = " + loginList.get(0).getClass());
                                Logg.i("loginList.get(0) = " + loginList.get(0).get("original").getClass());

                                Global.HEADER = loginList.get(0).get("original").get("token_type") + " " + loginList.get(0).get("original").get("access_token");
                                startActivity(MainActivity.class);
                                finish();
                            }
                        } else {
//                            startActivity(MainActivity.class);
                            if (TextUtils.equals("4001", baseResult2.getCode())) {// 注册成功,完善信息
                                LinkedTreeMap<String, Integer> user = (LinkedTreeMap) baseResult2.getData();
                                String tmp = user.get("id") + "";
                                if (tmp.contains(".")) {
                                    Global.USER_ID = tmp.substring(0, tmp.lastIndexOf("."));
                                } else {
                                    Global.USER_ID = tmp;
                                }
                                Logg.i("Global.USER_ID = " + Global.USER_ID);
                                startActivity(RealAuthAgentActivity.class);
                                LOGIN_TYPE = 0;// 登录类型设置为普通
                            }
                        }
                        ToastUtils.showShort(baseResult2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("登录失败");
                    }
                });
    }

    // 微信登录
//    private Disposable reqWxLogin(){
//        return APIRetrofit.getDefault().wxLogin();
//    }
}